# # -*- coding: utf-8 -*-
#
# from flask.ext.redis import FlaskRedis
# from contrib.sms_provider import  FlaskSMS
# from contrib.gps_provider import  FlaskGpsProvider
# redis_store = FlaskRedis()
# sms_provider = FlaskSMS()
# gps_provider = FlaskGpsProvider()
#
# oss_path = ''
#
# #
# # def change_weibo_header(uri, headers, body):
# #     auth = headers.get('Authorization')
# #     if auth:
# #         auth = auth.replace('Bearer', 'OAuth2')
# #         headers['Authorization'] = auth
# #     return uri, headers, bod

from flask_marshmallow import Marshmallow
from flask_redis import FlaskRedis

redis_store = FlaskRedis()
import random


def next_id(code):
    next_key = 'REDIS_NEXT_ID2_{}'.format(code)

    with  redis_store.pipeline() as pipe:
        while 1:
            try:
                next_value = redis_store.incr(next_key)
                if next_value > 100000: return next_value
                pipe.watch(next_key)
                # current_value = pipe.get(next_key)
                # if current_value is None:
                current_value = random.randint(100000, 999999)
                next_value = int(current_value) + 1
                pipe.multi()
                pipe.set(next_key, next_value)
                pipe.execute()
                return next_value
            except Exception:
                continue
                # return redis_store.incr('NEXT_ID_{}'.format(code))


marshmallow = Marshmallow()


def get_ip_country_and_city(ip):
    import geoip2.database
    import os

    with(geoip2.database.Reader(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'conf/GeoLite2-City.mmdb'),
                                'zh-CN')) as reader:
        try:
            res = reader.city(ip)
            return res.country, res.city
        except geoip2.errors.AddressNotFoundError:
            return None


if __name__ == '__main__':
    print(get_ip_country_and_city('192.30.253.112'))
